//
//  MainViewController.m
//  UI16_断点续传_后台传输
//
//  Created by yuewang on 16/1/28.
//  Copyright © 2016年 yuewang. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController () <NSURLSessionDownloadDelegate, UIApplicationDelegate>

@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) UILabel *label;

@property (nonatomic, retain) NSURLSessionDownloadTask *task;
@property (nonatomic, retain) NSURLSession *session;

@property (nonatomic, retain) NSData *data;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self addSubviews];

}

// 视频地址: http://us.sinaimg.cn/003kyKo0jx06VEIpDJgA05040100WKL30k01.mp4

- (void)initData {
    self.data = [NSData data];
    
}


- (void)addSubviews {
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(40, 100, self.view.frame.size.width - 80, 50)];
    [self.view addSubview:self.textField];
    [_textField release];
    
    self.textField.placeholder = @"请输入下载URL";
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    
    UIButton *startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:startBtn];
    
    startBtn.frame = CGRectMake(50, 200, (self.view.frame.size.width - 100) / 2 - 2, 40);
    startBtn.backgroundColor = [UIColor lightGrayColor];
    [startBtn setTitle:@"Download" forState:UIControlStateNormal];
    [startBtn addTarget:self action:@selector(startBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *stopBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:stopBtn];
    
    stopBtn.frame = CGRectMake(50 + (self.view.frame.size.width - 100) / 2, 200, (self.view.frame.size.width - 100) / 2 - 2, 40);
    stopBtn.backgroundColor = [UIColor lightGrayColor];
    [stopBtn setTitle:@"Stop" forState:UIControlStateNormal];
    [stopBtn addTarget:self action:@selector(stopBtnClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(40, 300, self.view.frame.size.width - 80, 100)];
    [self.view addSubview:self.label];
    [_label release];
    self.label.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.8];
    self.label.numberOfLines = 2;
}

#pragma mark - 知识点1 断点续传
/**
 *  思路:1. 点击Stop停止下载, 存储当前下载数据, 以便后来继续下载.
 *      2. 点击Download继续下载, 需判断是初次下载还是继续下载.
 */
/** 1. 暂停下载 */
- (void)stopBtnClicked {
    if (self.task != nil) {
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            self.data = resumeData;
        }];
        self.task = nil;
    }
}

/** 2. 开始下载 / 继续下载 */
- (void)startBtnClicked {
    if (self.session != nil && self.data != nil) {
        self.task = [self.session downloadTaskWithResumeData:self.data];
        
    } else {
        NSURL *url = [NSURL URLWithString:self.textField.text];
    
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"currentURL"];
        configuration.discretionary = YES;
    
        self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
        self.task = [self.session downloadTaskWithURL:url];
    }
    [self.task resume];
}

#pragma mark - 实现协议方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {

    NSString *pathExtention = [NSURL URLWithString:self.textField.text].pathExtension;
    
    NSURL *goalLocation = [NSURL URLWithString:[@"file://" stringByAppendingString:[NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/aa.%@", pathExtention]]]];

    NSError *errorOfStoryFile = nil;
    
    NSLog(@"存储地址:%@", goalLocation);
    
    [[NSFileManager defaultManager] copyItemAtURL:location toURL:goalLocation error:&errorOfStoryFile];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    self.label.text = [NSString stringWithFormat:@"当前传输的字节数:%lld\n共需传输字节数:%lld", totalBytesWritten, totalBytesExpectedToWrite];
}

#pragma mark - 知识点2 设置传输
/** 1. 设置允许应用后台运行
 *  Capbilities-->开启"Background Modes"
 */
/* 2. 告知代理人, 应用将从未激活状态变为激活状态 */
- (void)applicationDidBecomeActive:(UIApplication *)application {
    application.applicationIconBadgeNumber = 0;
}

/* 3. 重新链接到原URL的session中, 对用户界面修改. */
- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
    /* 告知系统, app用户界面发生变化, 可重新生成新的屏幕快照 */
    completionHandler();
}

-(void)dealloc {
    [_textField release];
    [_label release];
    [_task release];
    [_session release];
    [_data release];
    [super dealloc];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
